<template>
  <div class="staffManagement h100">
    <div class="PageContent">
      <el-row style="text-align: left; line-height: 4em">
        <el-button
          type="primary"
          v-if="btnRight.btnStaffManagementRefresh"
          @click="refresh()"
          >刷新</el-button
        >
        <el-button
          type="primary"
          v-if="btnRight.btnStaffManagementAdd"
          @click="add()"
          >添加</el-button
        >
        <el-button
          type="primary"
          v-if="btnRight.btnStaffManagementEdit"
          @click="modify()"
          >修改</el-button
        >
        <el-button
          type="danger"
          v-if="btnRight.btnStaffManagementDelete"
          @click="remove()"
          >删除</el-button
        >
      </el-row>
      <el-row>
        <el-form
          :model="searchData"
          :inline="true"
          label-width="80px"
          :rules="rules"
          ref="searchData"
          class="demo-ruleForm"
        >
          <el-row :gutter="5" class="fileSearch">
            <el-form-item label="工号:" prop="jobNo">
              <el-input v-model="searchData.jobNo" maxlength="50"></el-input>
            </el-form-item>
            <el-form-item label="姓名:" prop="fullName">
              <el-input v-model="searchData.fullName" maxlength="50"></el-input>
            </el-form-item>
            <el-form-item label="所属公司:" prop="companyName">
              <el-input
                v-model="searchData.companyName"
                maxlength="50"
              ></el-input>
            </el-form-item>
            <el-form-item label="所属部门:" prop="departmentName">
              <el-input
                v-model="searchData.departmentName"
                maxlength="50"
              ></el-input>
            </el-form-item>
            <el-form-item label="状态:" prop="disableState">
              <el-select v-model="searchData.disableState" placeholder="请选择">
                <el-option
                  v-for="item in State"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSearch('search')"
                >查询</el-button
              >
              <el-button @click="search('searchData')">重置</el-button>
            </el-form-item>
          </el-row>
        </el-form>
      </el-row>
      <el-table
        ref="staffTable"
        :data="tableData"
        :header-cell-style="{
          background: 'rgb(222,225,230)',
          color: '#606266',
        }"
        border
        @row-click="handleRowClick"
        @select="select"
        @select-all="selectAll"
        :height="tableHeight"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column
          property="jobNo"
          label="工号"
          align="center"
          width="220"
        >
        </el-table-column>
        <el-table-column
          property="fullName"
          label="姓名"
          align="center"
          width="120"
        >
        </el-table-column>
        <el-table-column
          property="userGender"
          label="性别"
          align="center"
          width="120"
        >
        </el-table-column>
        <el-table-column
          property="mobilePhone"
          label="手机"
          align="center"
          width="120"
        >
        </el-table-column>
        <el-table-column
          property="otherPhone"
          label="其他电话"
          align="center"
          width="120"
        >
        </el-table-column>
        <el-table-column property="companyName" label="所属公司" align="center">
        </el-table-column>
        <el-table-column
          property="departmentName"
          label="所属部门"
          align="center"
          width="300"
        >
        </el-table-column>
        <el-table-column
          prop="disableState"
          align="center"
          label="状态"
          width="150"
        >
          <template slot-scope="{ row, $index }">
            <p v-if="row.disableState == 0">
              <span>有效可用</span>
            </p>
            <p v-else-if="row.disableState == 1">
              <span>无效禁用</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="resetPassword(scope.row.id)"
              >重置密码</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <p style="text-align: center; margin-top: 20px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pager.currentPage"
          :page-size="pager.pageSize"
          background
          layout="prev, pager, next, jumper"
          :total="pager.total"
        >
        </el-pagination>
      </p>
    </div>
    <el-dialog
    class="person_dialog"
      title="员工信息维护"
      :visible.sync="dialogVisible"
      width="700px"
      v-dialogDrag
      border
      @closed="closedDialog"
    >
      <el-form
        :model="saveData.accountUser"
        class="saveform"
        :rules="rules"
        ref="staffForm"
        :inline="true"
        label-width="120px"
        :disabled="saveFlag"
      >
        <el-row :gutter="5">
          <el-col :span="12">
            <el-form-item label="工号:" prop="jobNo">
              <el-input
                v-model="saveData.accountUser.jobNo"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- 新增 密码 -->
          <el-col :span="12" v-if="addFlag" id="add">
            <el-form-item label="登录密码:" prop="loginPassword">
              <el-input
                v-model="saveData.accountUser.loginPassword"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- 修改 不展示密码 -->
          <!-- <el-col :span="12" v-else id='edit'>
            <el-form-item label="登录密码:" prop="loginPassword">
              <el-input
                v-model="saveData.accountUser.loginPassword"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="姓名:" prop="fullName">
              <el-input
                v-model="saveData.accountUser.fullName"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别:">
              <el-select
                v-model="saveData.accountUser.userGenderCode"
                onkeydown="return (event.keyCode!=8)"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in saveData.dicts.sex_simple"
                  :key="item.dataCode"
                  :label="item.dataText"
                  :value="item.dataCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机:" prop="mobilePhone">
              <el-input
                v-model="saveData.accountUser.mobilePhone"
                onkeyup="value= (value.match(/^\d*(\.?\d{0,2})/g)[0]) || null"
                maxlength="11"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="其他电话:">
              <el-input
                v-model="saveData.accountUser.otherPhone"
                maxlength="255"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="联系地址:">
            <el-input
              type="textarea"
              style="width: 532px"
              v-model="saveData.accountUser.address"
              maxlength="255"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item
            label="公司部门"
            class="company_item"
            :prop="companyModify ? 'companyDepartment' : 'organizationFullName'"
          >
            <el-input
              v-model="saveData.accountUser.organizationFullName"
              v-show="!companyModify"
              class="modify"
              :disabled="true"
            >
            </el-input>
            <el-cascader
              v-show="companyModify"
               filterable
              placeholder="请选择公司/部门"
              :options="companyDepartmentOptions"
              :props="{ expandTrigger: 'hover', checkStrictly: true }"
              v-model="saveData.accountUser.companyDepartment"
              clearable
              @change="handleCompanyChange"
            ></el-cascader>
          </el-form-item>
          <!-- <el-form-item label="公司:">
            <el-select v-model="saveData.accountUser.companyId" @change="companyIdChange" placeholder="请选择" >
              <el-option v-if="organization&&organization.length"
                         v-for="(item,index) in organization"
                         :key="index"
                         :label="item.gongsi"
                         :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="部门:">
            <el-select v-model="saveData.accountUser.departmentId" placeholder="请选择" >
              <el-option v-if="bumen&&bumen.length"
                         v-for="(item,index) in bumen"
                         :key="index"
                         :label="item.organizationName"
                         :value="item.id"/>
            </el-select>
          </el-form-item> -->
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="状态:">
            <el-select
              v-model="saveData.accountUser.disableState"
              onkeydown="return (event.keyCode!=8)"
              placeholder="请选择"
            >
              <el-option
                v-for="item in disableState"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="排序:">
            <el-input
              onkeyup="value= (value.match(/^\d*(\.?\d{0,2})/g)[0]) || null"
              v-model="saveData.accountUser.sort"
              :maxlength="11"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="IC卡卡号:">
            <el-input
              v-model="saveData.accountUser.icCardCode"
              maxlength="255"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              v-model="saveData.accountUser.remark"
              v-if="btnRight.btnStaffManagementReadCard"
              @click="$message('暂无规则')"
              >读取卡号</el-button
            >
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="备注:">
            <el-input
              type="textarea"
              v-model="saveData.accountUser.remark"
              style="width: 532px"
            ></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button
          type="primary"
          v-if="btnRight.btnStaffManagementSave"
          @click="save()"
          :disabled="saveFlag"
          >保存</el-button
        >
        <el-button
          v-if="btnRight.btnStaffManagementCancel"
          @click="dialogVisible = false"
          >取 消</el-button
        >
      </div>
    </el-dialog>
    <!-- 修改密码弹框 -->
    <el-dialog v-dialogDrag
      border class="reset_password_dialog" title="重置密码" width="30%" label-width="80px" :visible.sync="resetPasswordDialog" @close="closeResetPasswordDialog">
      <el-form class="reset_password_form" ref='resetPasswordForm' :model="resetPasswordForm" :rules="resetPasswordFormRules">
        <el-form-item label="新密码" prop="password">
          <el-input type="password" placeholder="请输入新密码" v-model="resetPasswordForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="8" :offset="16">
             <el-form-item>
              <el-button type="primary" @click="submitResetPasswordForm('resetPasswordForm')">确 定</el-button>
              <el-button @click="resetPasswordDialog = false">取 消</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import * as API from "@/api/stystemManagement";
import axios from "axios";
export default {
  name: "staffManagement",
  data() {
    return {
      resetPasswordDialog:false,//重置密码弹框
      resetPasswordForm:{
        password:''
      },//重置密码表单
      resetPasswordFormRules:{
        password:[
          {
            required: true,
            message: "请输入密码",
            transform: (value) => value,
            trigger: "blur",
          },
          {
            type: "string",
            message: "请输入不包含空格的字符",
            trigger: "blur",
            transform(value) {
              if (value && value.indexOf(" ") === -1) {
                return value;
              } else {
                return false;
              }
            },
          },
          {
            trigger: "blur",
            validator: (rule, value, callback) => {
              var passwordreg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/;
              if (!passwordreg.test(value)) {
                /*  alert('密码必须由数字、字母组合,请输入6-16位')*/
                callback(new Error("密码由数字、字母组合,请输入6-16位"));
              } else {
                callback();
              }
            },
          },
        ]
      },//重置密码校验规则
      resetPasswordUserId:'',//需要重置密码的用户id
      rules: {
        loginPassword: [
          {
            required: true,
            message: "请输入密码",
            transform: (value) => value,
            trigger: "blur",
          },
          {
            type: "string",
            message: "请输入不包含空格的字符",
            trigger: "blur",
            transform(value) {
              if (value && value.indexOf(" ") === -1) {
                return value;
              } else {
                return false;
              }
            },
          },
          {
            trigger: "blur",
            validator: (rule, value, callback) => {
              var passwordreg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/;
              if (!passwordreg.test(value)) {
                /*  alert('密码必须由数字、字母组合,请输入6-16位')*/
                callback(new Error("密码由数字、字母组合,请输入6-16位"));
              } else {
                callback();
              }
            },
          },

          /* {required: true, message: '请填写密码', trigger: 'blur'},*/
        ],
        mobilePhone: [
          {
            pattern: /^1[0-9]{10}$/,
            message: "请输入正确的电话号码",
            trigger: "blur",
          },
        ],
        jobNo: [{ required: true, message: "请填写工号", trigger: "blur" }],

        fullName: [{ required: true, message: "请填写姓名", trigger: "blur" }],
        companyDepartment: [
          {
            type: "array",
            required: true,
            message: "请选择公司/部门",
            trigger: "change",
          },
        ],
        organizationFullName: [
          { required: true, message: "请选择公司/部门", trigger: "change" },
        ],
      },
      allCompanyData: [],
      companyModify: true, //公司部门新增为true
      companyDepartmentOptions: [], //组织机构数据
      companyDepartment: [], //所选组织部门
      // organizationFullName:'',//公司单位名字
      treeData: [
        {
          id: 0,
          label: "组织机构",
          children: [],
        },
      ],
      tableSelection: [],
      searchData: {
        jobNo: "",
        fullName: "",
        companyName: "",
        departmentName: "",

        disableState: 0,
        pageSize: 0,
        currentPage: 0,
        exportExcelFlag: 0,
        orderField: "",
        orderType: "",
      },

      //**数据**//
      tableData: [],
      tableHeight: 0,
      pager: {
        pageSize: 20,
        total: 1,
        currentPage: 1,
      },
      showRule: [], //根据车辆类型选择显示相应规则
      purpose: [],
      saveData: {
        accountUser: {
          id: 0,
          jobNo: "",
          loginPassword: "",
          fullName: "",
          userGenderCode: "",
          mobilePhone: "",
          organizationFullName: "", //公司部门
          otherPhone: "",
          address: "",
          companyId: "",
          departmentId: "",
          disableState: 0,
          sort: "",
          companyDepartment: [],
          icCardCode: "",
          remark: "",
          version: 0,
        },
        dicts: {},
        organizations: [],
      },
      disableState: [
        { label: "有效可用", value: 0 },
        { label: "无效禁用", value: 1 },
      ],
      State: [
        { label: "全部", value: -1 },
        { label: "有效可用", value: 0 },
        { label: "无效禁用", value: 1 },
      ],
      addFlag: true, //新增为true，修改false
      dialogVisible: false, //礼厅对话框
      saveFlag: false, //礼厅保存标志,
      onpresscTime: 0, //  阻止短时间内连续点击
      organization: [], //部门公司分级
      bumen: [], //当前公司部门
      btnRight: {
        btnStaffManagementAdd: true, //添加
        btnStaffManagementEdit: true, //修改
        btnStaffManagementDelete: true, //删除
        btnStaffManagementSave: true, //保存
        btnStaffManagementCancel: true, //取消
        btnStaffManagementRefresh: true, //刷新
        btnStaffManagementReadCard: true, //读取卡号
      },
    };
  },
  //inject:['reload'],
  created() {
    this.onSearch();
    //console.log("create")
    // this.loadAccountUserListData();
  },
  mounted() {
    this.loadOrganizationTreeWithParentIdData();
    //载入按钮
    this.btnRight = this.$route.meta.buttons;
    //遍历属性赋值将true与false字符串转换成布尔型的值
    for (let key of Object.keys(this.btnRight)) {
      this.btnRight[key] =
        this.btnRight[key] || this.btnRight[key] == "true" ? true : false;
    }
    var that = this;
    window.onresize = function () {
      var search = document.getElementsByClassName("fileSearch")[0]
        .offsetHeight;
      var dom = document.getElementsByClassName("PageContent")[0].offsetHeight;
      that.tableHeight = dom - search - 180;
    };
  },
  watch: {
    dialogVisible() {
      if (this.dialogVisible == false) {
        this.$nextTick(() => {
          this.$refs.staffForm.resetFields();
        });
      }
    },
  },
  //注销window.onresize事件
  destroyed() {
    window.onresize = null;
  },
  updated() {
    this.$nextTick(() => {
      var dom = document.getElementsByClassName("PageContent")[0].offsetHeight;
      var search = document.getElementsByClassName("fileSearch")[0]
        .offsetHeight;
      this.tableHeight = dom - search - 180;
    });
  },
  methods: {
    //重置表單
    /*resetLoginForm () {
        /!*this.$refs.loginFormRef.resetFields()*!/
        this.refresh()
      },*/
      //关闭重置密码弹框
      closeResetPasswordDialog(){
        this.$refs.resetPasswordForm.resetFields()
      },
      //重置密码表单提交
      submitResetPasswordForm(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm('您确认重置密码?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async () => {
              let postData={
                type:"sysUser",
                uid:this.resetPasswordUserId,
                pwd:this.resetPasswordForm.password
              }
              const res= await API["resetAccountUserPassword"](postData)
              console.log(res,"重置密码结果")
              if(res.code===1){
                this.resetPasswordDialog=false;
                this.$message({
                  type: 'success',
                  message: res.message
                });
              }else{
                this.$message({
                  type: 'error',
                  message: '重置密码失败！'
                });
              }
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消重置'
              });
            });

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
    resetPassword(id) {
      this.resetPasswordUserId=id;
      this.resetPasswordDialog=true
      //  this.$confirm('您确定重置密码吗?', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      //       //展示重置密码弹框
      //       this.resetPasswordDialog=true
      //     })
      //     .catch(action => {
      //       console.log('取消')
      //       this.$message("您取消了该操作")
      //     });
    },
    //监听弹框关闭
    closedDialog() {
      this.companyModify = true;
         this.saveData= {
          accountUser: {
            id: 0,
            jobNo: "",
            loginPassword: "",
            fullName: "",
            userGenderCode: "",
            mobilePhone: "",
            organizationFullName: "", //公司部门
            otherPhone: "",
            address: "",
            companyId: "",
            departmentId: "",
            disableState: 0,
            sort: "",
            companyDepartment: [],
            icCardCode: "",
            remark: "",
            version: 0,
          },
          dicts: {},
          organizations: [],
        }
    },
    //递归获得树的子集
    getChildren(node, data) {
      let this_get = this;
      let child = new Array();
      if (this_get.checkIsNode(node, data)) {
        if (data && data.length) {
          data.forEach((item) => {
            if (node.id == item.parentId && item.label) {
              let nodeItem = {
                id: item.id,
                label: item.label,
                value: item.id,
                // positionName: item.positionName
              };
              if (this_get.checkIsNode(nodeItem, data)) {
                if (!nodeItem.children) {
                  nodeItem.children = new Array();
                }
                nodeItem.children.push(this_get.getChildren(nodeItem, data));
              }
              child.push(nodeItem);
            }
          });
          node.children = child;
          return node;
        }
      } else {
        return node;
      }
    },
    //判断是否是节点
    checkIsNode(node, data) {
      let flag = false;
      if (data && data.length && data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          if (node.id == data[i].parentId) {
            flag = true;
            return flag;
          }
        }
      }
      return flag;
    },
    //加载树
    loadOrganizationTreeWithParentIdData() {
      let postData = {
        id: 0,
      };
      API["loadOrganizationTreeWithParentId"](postData)
        .then((response) => {
          const { data } = response;
          // this.treeData[0].children = data;
          let node = {
            id: 0,
            label: "组织机构",
            children: [],
          };
          this.allCompanyData = data;
          console.log(data, "没改变");
          let arr = this.getChildren(node, data);

          this.treeData = [arr];

          this.companyDepartmentOptions = this.treeData[0].children;
          console.log("组织", this.companyDepartmentOptions);
        })
        .catch((error) => {
          this.$message(error);
        });
    },
    //部门级联选择器
    handleCompanyChange(val) {
      this.companyDepartment = val;
      this.saveData.accountUser.companyId = val[val.length - 2];
      this.saveData.accountUser.departmentId = val[val.length - 1];
      console.log("部门改变", val);
    },
    search(formName) {
      this.$refs[formName].resetFields();
      this.loadAccountUserListData();
      // location.reload()
    },
    //点击行触发，选中或不选中复选框
    handleRowClick(row, column, event) {
      if (this.tableSelection.length > 0) {
        this.$refs.staffTable.toggleRowSelection(this.tableSelection[0], false);
      }
      this.$refs.staffTable.toggleRowSelection(row);
      this.tableSelection = [row];
    },
    select(selection, row) {
      // 选择项大于1时
      if (selection.length > 1) {
        let del_row = selection.shift();
        // console.log('把数组的第一个元素从其中删除后', selection);
        this.$refs.staffTable.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
      }
      this.tableSelection = selection;
    },
    selectAll(selection) {
      if (selection.length > 1) {
        selection.length = 1;
      }
      this.tableSelection = selection;
    },
    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange: function (size) {
      this.pager.pagesize = size;
    },
    handleCurrentChange: function (currentPage) {
      this.pager.currentPage = currentPage;
      this.loadAccountUserListData(); //点击第几页
    },
    /**********************方法**********************/
    //查询
    onSearch(value) {
      this.loadAccountUserListData(value);
    },
    refresh() {
      this.loadAccountUserListData();
    },
    //table中类型添加
    add() {
      this.addFlag = true;
      this.saveData.accountUser = {
        id: 0,
        jobNo: "",
        loginPassword: "",
        fullName: "",
        userGenderCode: "",
        mobilePhone: "",
        otherPhone: "",
        address: "",
        companyId: "",
        departmentId: "",
        disableState: 0,
        sort: "",
        icCardCode: "",
        remark: "",
        version: 0,
      };
      let postData = {
        id: null,
        dictTypeCodes: ["equipment_type"],
      };
      this.loadAccountUserWithIdData(null).then((res) => {
        if (res.dicts) {
          this.saveData.dicts = res.dicts;
        }
        if (res.organizations) {
          this.saveData.organizations = res.organizations;
          this.AccountUserSort(res.organizations);
        }
        this.dialogVisible = true;
      });
    },
    //table中类型修改
    modify() {
      this.companyModify = false;
      let data = this.$refs.staffTable.selection;
      if (data.length == 0) {
        this.$message("未选中");
        return;
      }
      this.loadAccountUserWithIdData(data[0].id).then((res) => {
        console.log(res.accountUser,"修改")
        if (res.accountUser) {
          this.saveData.accountUser = JSON.parse(
            JSON.stringify(res.accountUser)
          );
          if (
            this.saveData.accountUser.companyId == 0 ||
            this.saveData.accountUser.companyId == "0"
          ) {
            this.saveData.accountUser.companyId = "";
          }
          if (
            this.saveData.accountUser.departmentId == 0 ||
            this.saveData.accountUser.departmentId == "0"
          ) {
            this.saveData.accountUser.departmentId = "";
          }
          // this.companyIdChange(res.accountUser.companyId)
          // this.departmentIdChange(res.accountUser.departmentId)
          //this.organizationFullName=this.saveData.accountUser.organizationFullName
        }
        if (res.dicts) {
          this.saveData.dicts = res.dicts;
        }
        if (res.organizations) {
          this.saveData.organizations = res.organizations;
          this.AccountUserSort(res.organizations);
        }
        // if (this.saveData.accountUser.companyId){
        //this.companyIdChange(this.saveData.accountUser.companyId)
        //   /*调用companyIdChange时departmentId会清空，companyId改变时调用companyIdChange方法*/
        //   //this.saveData.accountUser.departmentId = res.accountUser.departmentId == 0?'':res.accountUser.departmentId
        // }
        this.addFlag = false;
        this.dialogVisible = true;
      });
    },
    //table中删除
    remove() {
      let data = this.$refs.staffTable.selection;
      if (data.length == 0) {
        this.$message("未选中");
        return;
      }
      this.$confirm("删除信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let postData = [
            {
              id: data[0].id,
              version: data[0].version,
            },
          ];
          API["deleteAccountUserWithId"](postData)
            .then((response) => {
              const { message } = response;
              this.tableSelection = [];
              this.$message(message);
              this.loadAccountUserListData();
            })
            .catch((error) => {
              this.$message(error);
            });
        })
        .catch(() => {
          //几点取消的提示
        });
    },
    //加载
    loadAccountUserWithIdData(id) {
      let postData = {
        id: id,
        dictTypeCodes: ["sex_simple"],
      };
      return new Promise((resolve) => {
        API["loadAccountUserWithId"](postData)
          .then((response) => {
            const { data } = response;
            if (!data) {
              this.$message("数据读取失败");
              return;
            }
            resolve(data);
          })
          .catch((error) => {
            this.$message(error);
          });
      });
    },
    //加载列表
    loadAccountUserListData(value) {
      if (value) {
        this.pager.currentPage = 1;
      }
      let postData = {
        jobNo: this.searchData.jobNo,
        pageSize: this.pager.pageSize,
        currentPage: this.pager.currentPage,
        fullName: this.searchData.fullName,
        companyName: this.searchData.companyName,
        orderField: this.searchData.orderField,
        departmentName: this.searchData.departmentName,
        orderType: this.searchData.orderType,
        disableState: this.searchData.disableState,
      };
      API["loadAccountUserList"](postData)
        .then((response) => {
          const { data } = response;
          if (!data) {
            this.$message("数据读取失败");
            return;
          }
          this.tableData = data.list;
          this.pager.pageSize = data.pager.pageSize;
          this.pager.total = data.pager.total;
          this.pager.currentPage = data.pager.currentPage;
        })
        .catch((error) => {
          this.$message(error);
        });
    },
    //保存信息
    save() {
      if (Date.now() - this.onpresscTime > 2000) {
        this.onpresscTime = Date.now();
        console.log(Date.now());
      } else {
        return;
      }
      this.$refs.staffForm.validate((valid) => {
        if (valid) {
          this.saveFlag = true;
          this.saveAccountUserData();
        } else {
          return false;
        }
      });
    },
    saveAccountUserData() {
      let postData = this.saveData.accountUser;
      API["saveAccountUser"](postData)
        .then((response) => {
          const { message } = response;
          this.$message(message);
          this.loadAccountUserListData();
          this.dialogVisible = false;
          this.saveFlag = false;
        })
        .catch((error) => {
          this.$message(error);
          this.saveFlag = false;
        });
    },
    /**********************方法**********************/
    //根据parentId分别取公司和部门的集合
    AccountUserSort(data) {
      // organization:[
      //   {gongsi: "公司二级", id: 40, parentId: 0, bumen: Array(3), organizationAbbreviation: null},
      //   {gongsi: "公司三级", id: 41, parentId: 0, bumen: Array(3), organizationAbbreviation: null},
      // ]
      let gongsi = [];
      if (data && data.length) {
        //首先遍历所有的公司
        data.forEach((item) => {
          if (item.parentId == 0) {
            let obj = {};
            obj.gongsi = item.organizationName;
            obj.id = item.id;
            obj.parentId = 0;
            obj.bumen = [];
            obj.organizationAbbreviation = item.organizationAbbreviation;
            gongsi.push(obj);
          }
        });
        //遍历部门
        if (gongsi && gongsi.length) {
          gongsi.forEach((gs) => {
            data.filter((item) => {
              if (gs.id == item.parentId) {
                gs.bumen.push(item);
              }
            });
          });
        }
        this.organization = gongsi;
        if (
          this.saveData.accountUser.departmentId &&
          this.saveData.accountUser.companyId
        ) {
          this.organization.forEach((item) => {
            if (item.id == this.saveData.accountUser.companyId) {
              this.bumen = item.bumen;
            }
          });
        }
        // this.bumen = this.organization[0].bumen
      }
    },
    // companyIdChange(data){
    //   this.bumen = []
    //   this.saveData.accountUser.departmentId = ""
    //   if (data){
    //     this.organization.forEach(item=>{
    //       if (item.id == data){
    //         this.bumen = item.bumen
    //       }
    //     })
    //   } else
    //     this.bumen = []
    // },
    //根据返回的公司ID遍历查出组织名字
    // companyIdChange(id){
    //   this.companyDepartmentOptions.forEach(item=>{
    //     if(item.id==id){
    //       this.organizationFullName=item.label
    //     }
    //   })
    //   console.log(this.organizationFullName,'公司名字')
    // },
    // departmentIdChange(id){
    //   this.allCompanyData.forEach(item=>{
    //     if(item.id==id){
    //       if(this.organizationFullName!=''){
    //         this.organizationFullName+='/'+item.label
    //       }else{
    //         this.organizationFullName+=item.label
    //       }

    //     }
    //   })
    //   console.log(this.organizationFullName,'单位名字')
    // },
    //验证整数
    onlySortNumber() {
      // 先把非数字的都替换掉，除了数字和.
      let obj = this.saveData.accountUser.sort;
      obj = Number.parseInt(obj);
      this.saveData.accountUser.sort = obj;
    },
  },
};

/*var loginPassword = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$/;  //校验密码6-18位
  if (!phoneTest.test(this.loginRuleForm.userName && this.loginRuleForm.repeat_Password)) {
    this.$message.error('密码须包含数字、字母两种元素，且密码位数为6-16位');
    return false;
  }*/
</script>

<style scoped>
.wrapper {
  display: flex;
  flex-wrap: nowrap;
  margin: 5px 0px;
  justify-content: space-between;
}
.staffManagement .person_dialog /deep/ .el-dialog__body {
  padding: 20px 0;
}
.reset_password_dialog /deep/ .el-dialog__body {
  padding: 20px;
}
.reset_password_dialog .el-row .el-col /deep/ .el-form-item{
  margin-bottom: 0;
}
.box-card {
  flex: 0 0 200px;
  display: inline-block;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 0px;
  margin-right: 30px;
}
.item {
  font-size: 16px;
  font-weight: 400;
  height: 90px;
  line-height: 30px;
  text-align: left;
  padding: 0 1em;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #e9e9e9;
}
.item:hover {
  cursor: pointer;
}
.item:last-child {
  margin-bottom: 0px;
}
.item.sale {
  background-color: #ff6040;
}
.item.free {
  background: white;
}
.item.repair {
  background: yellow;
}
.ruleItem {
  width: 532px;
  max-height: 6em;
  overflow-y: auto;
  line-height: 1.5em;
}
.ruleItem .content {
  width: 100%;
  padding-top: 10px;
}
.tablestyle {
  width: 100%;
  height: calc(100% - 220px);
  overflow-y: scroll;
}
.company_item /deep/ .el-form-item__content {
  width: 530px;
}
.company_item /deep/ .el-form-item__content .el-cascader {
  width: 100%;
}
.reset_password_form /deep/ .el-input{
  width: 80%;
}
@media screen and (max-width: 605px) {
  /*当屏幕尺寸小于600px时，应用下面的CSS样式*/
  .tablestyle {
    height: calc(100% - 450px);
  }
}

@media screen and (min-width: 606px) and (max-width: 884px) {
  /*当屏幕尺寸小于600px时，应用下面的CSS样式*/
  .tablestyle {
    height: calc(100% - 310px);
  }
}
@media screen and (min-width: 885px) and (max-width: 1094px) {
  /*当屏幕尺寸小于600px时，应用下面的CSS样式*/
  .tablestyle {
    height: calc(100% - 280px);
  }
}
@media screen and (min-width: 1095px) and (max-width: 1751px) {
  /*当屏幕尺寸小于600px时，应用下面的CSS样式*/
  .tablestyle {
    height: calc(100% - 270px);
  }
}
</style>

